package com.yss.threadpool;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

/**
 * Thread Pool
 */
public class ThreadPoolFactory {

    private final static int _CoreSize = 10;
    private final static int _MaxThreadSize = 200;

    private static volatile ThreadPoolExecutor pool = null;

    public static ThreadPoolExecutor getInstance() {
        if (pool == null) {
            synchronized (ThreadPoolFactory.class) {
                if (pool == null) {
                    pool = new ThreadPoolExecutor(_CoreSize, _MaxThreadSize, 60 * 1000L, TimeUnit.SECONDS,
                            new LinkedBlockingQueue<>(), new ThreadFactory() {
                        private final AtomicLong atomicLong = new AtomicLong(0L);

                        @Override
                        public Thread newThread(Runnable runnable) {
                            String threadName = String.format("event-sender-thread-%d", atomicLong.getAndIncrement());
                            return new Thread(runnable, threadName);
                        }
                    }, new ThreadPoolExecutor.CallerRunsPolicy());
                }
                return pool;
            }
        }
        return pool;
    }
}
